// proxyUsageRate.js
const app = getApp()
const util = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    level:null,
    search: {
      Show: false,
      searchTip: '可输入ID、名称等',
      searchValue: '',
    },
    searchRecord: [],
    sort: true,//true : descending,false : ascending
    currentTab: '0',
    tablineStyle: '',

    timeList: [],
    timeSelect: 29,//选择的时间列表下标
    timeWidth:'',

    selectShow: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    selectData: ['天', '月'],//下拉列表的数据
    selectindex: 0,//选择的下拉列表下标

    list:[],
    pagenum: 1,
  },
  // 升降序切换
  sortChange:function(){
    this.setData({
      sort: !this.data.sort
    })
    this.useList();
  },
  // 切换tab
  tabChoose:function(e){
    var that = this;
    var cur = e.target.dataset.current;
    if (that.data.currentTab == cur) { return false; }
    else {
      that.setData({
        currentTab: cur,
        ['search.searchValue']:'',
        list: [],
        pagenum: 1
      })
    }
    that.tabLine();
    that.useList();
  },
  // 切换tab滑块动画
  tabLine:function(){
    var query = wx.createSelectorQuery();
    var that = this;
    var level = that.data.level;
    var tabtotal = (level == 1 || level == 2) ? 3 : 2 ;
    var currentTab = (level == 1 || level == 2) ? that.data.currentTab : ( that.data.currentTab == 0 ? 0 : 1 );
    query.select('.tab').boundingClientRect(function (rect) {
      that.setData({
        tablineStyle: "width:" + rect.width / tabtotal + "px;transform: translateX(" + rect.width * currentTab / tabtotal+"px);"
      })
    }).exec();
  },
  // 切换搜索界面显示状态
  toSearch: function () {
    this.setData({
      ['search.Show']: !this.data.search.Show,
      ['search.searchValue']:''
    })
  },
  // 绑定搜索输入框内容
  searchChange: function (event) {
    this.setData({
        ['search.searchValue']: event.detail
    })
  },
  // 搜索
  onSearch: function () {
    this.setData({
      ['search.Show']: !this.data.search.Show
    })
    this.saveRecord();
    this.getHistorySearch();
    this.useList();
  },
  // 获取历史搜索
  getHistorySearch: function () {
    this.setData({
      searchRecord: wx.getStorageSync('searchRecord') || [],//若无储存则为空
    })
  },
  //储存历史记录
  saveRecord: function () {
    var that = this
    var inputVal = that.data.search.searchValue
    var searchRecord = that.data.searchRecord
    if (inputVal == '') {
      //输入为空时的处理
    } else {
      // 重复的删除掉
      for (var index = 0; index < searchRecord.length; index++){
        if(inputVal == searchRecord[index].value){
          searchRecord.splice(index, 1)[0];
        }
      }
      //将搜索值放入历史记录中,只能放前12条
      if (searchRecord.length < 5) {
        searchRecord.unshift({
          value: inputVal,
          id: searchRecord.length
        })
      }
      else {
        searchRecord.pop()//删掉旧的时间最早的第一条
        searchRecord.unshift({
          value: inputVal,
          id: searchRecord.length
        })
      }
      //将历史记录数组整体储存到缓存中
      wx.setStorageSync('searchRecord', searchRecord)
    }
  },
  // 触发输入历史记录
  recordValue: function (event){
    var searchRecord = this.data.searchRecord;
    var index = event.currentTarget.dataset.index;
    this.setData({
      ['search.searchValue']: searchRecord[index].value
    })
  },
  // 点击垃圾桶删除历史纪录和本地储存
  historyDelFn: function () {
    wx.clearStorageSync('searhRecord')
    this.setData({
      searchRecord: []
    })
  },
  // 获取时间列表的长度
  timeWidth:function(){
    var query = wx.createSelectorQuery();
    var that = this;
    query.select('.timelist').boundingClientRect(function (rect) {
      that.setData({
        timeWidth: rect.width,
      })
    }).exec();
  },
  // 切换时间
  timeChoose: function (e) {
    var that = this;
    var index = e.target.dataset.timeindex;
    if (that.data.timeSelect == index) { return false; }
    else {
      that.setData({
        timeSelect: index
      })
      that.useList();
    }
  },
  // 点击下拉显示框
  selectTap() {
    this.setData({
      selectShow: !this.data.selectShow
    });
  },
  // 点击下拉列表
  optionTap(e) {
    let index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    this.setData({
      selectindex: index,
      selectShow: !this.data.selectShow
    });
    if (index == 0){
      this.arrayDay()
    }else if(index == 1){
      this.arrayMonth()
    }
    this.useList();

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      level:app.globalData.userInfo.level
    })
    this.getHistorySearch();
    this.tabLine();    
    this.arrayDay();
    this.useList();
  },
  // 获取列表
  useList: function (isScroll) {
    var that = this;
    if (isScroll !== 'scroll') {
      that.setData({ 
        list: [],
      })
    }
    var sort = that.data.sort == true ? 'desc' :'asc';
    var type = that.data.selectindex == 0 ? 'day' : 'month';
    var date = that.data.timeList[that.data.timeSelect].value;
    var url = that.data.currentTab == 0 ? 'Shop' : (that.data.currentTab == 1 ? 'Agent' : 'Device');
    var data = { 
      page: that.data.pagenum,
      input: that.data.search.searchValue,
      sort:sort,
      type: type,
      date: date,
      openid: app.globalData.openId
    };
    app.post('agent/usageAnalysisBy'+url, data).then((res) => {
      if (res.code == 200) {
        var dataArr = res.list;
        var list = that.data.list;
        list = list.concat(dataArr)
        that.setData({
          list: list
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);//错误提示信息
    })
    wx.stopPullDownRefresh()
  },
  // 去详情页
  ToDetailTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var that = this;
      if (that.data.currentTab == 0) {
        var id = that.data.list[index].id;
        wx.navigateTo({
          url: '../../pages/proxyUsageRateDetail/proxyUsageRateDetail?id=' + id + '&openid=' + app.globalData.openId + '&timeSelect=' + that.data.timeSelect + '&selectindex=' + that.data.selectindex,
        })
      } else if (that.data.currentTab == 1) {
        var openid = that.data.list[index].openid;
        wx.navigateTo({
          url: '../../pages/proxyAgentUsageRate/proxyAgentUsageRate?openid=' + openid,
        })
      }
    
    
  },
  // 获取当前日期的前30天（不包括当天）
  arrayDay: function () {
    var array_d = [];
    var obj = {}
    for (var i = 0; i < 30; i++) {
      var arr = util.formatdate( new Date(new Date().setDate(new Date().getDate() - i)) )
      obj = {
        value: arr,
        key:arr.substring(8,10)
      }
      array_d.unshift(obj)
    }
    this.setData({
      timeList:array_d,
      timeSelect: 29
    })
    this.timeWidth();
  },
  // 获取当前日期的前12月（不包括当月）
  arrayMonth: function () {
    var array_d = [];
    var obj = {}
    var d = new Date();
    for (var i = 0; i < 12; i++) {
      var m = d.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      obj = {
        value: d.getFullYear() + "-" + m,
        key: m.toString()
      }
      d.setMonth(d.getMonth() - 1);
      array_d.unshift(obj)
    }
    this.setData({
      timeList: array_d,
      timeSelect: 11
    })
    this.timeWidth();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      list: [],
      pagenum: 1,
      ['search.searchValue']: ''
    })
    this.onLoad();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var pagenum = that.data.pagenum + 1; //获取当前页数并+1
    that.setData({
      pagenum: pagenum, //更新当前页数
    })
    that.useList('scroll');//重新调用请求获取下一页数据
  }
})